package cn.bone.auth.security.base.advice;

import cn.bone.auth.security.base.exception.MyTestException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.nio.file.AccessDeniedException;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    //使用String做返回值,返回403页面
    @ExceptionHandler(AccessDeniedException.class)
    public String exception403(){
        // 403返回页面
        return "redirect:/403";
    }

    //使用ModelAndView做返回值,返回500页面
    @ExceptionHandler(Exception.class)
    public ModelAndView exception500(Exception e){
        // 500返回页面
        ModelAndView mv = new ModelAndView();
        //将异常信息放到request域中,基本上不会使用
        mv.addObject("errorMessage", e.getMessage());
        //其他异常
        // 500返回页面
        mv.setViewName("redirect:/500");
        return mv;
    }

    //返回json对象
    @ExceptionHandler(MyTestException.class)
    @ResponseBody
    public JSONObject myException(MyTestException e){

        JSONObject object = new JSONObject();
        object.put("message",e.getMessage());
        object.put("code","101");
        object.put("name","superbone");
        return object;
    }


}
